package org.vectrics.mail.struts;

import java.io.File;
import java.io.FileWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.common.util.FileUtil;
import org.vectrics.mail.FreeMarkerManager;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.user.Person;

public class LetterStagingManager {
	public static final String TEMPLATE_FILE_NAME = "template.dat";
	public static final String SUBJECT_FILE_NAME = "subject.dat";
	
	private Logger log = Logger.getLogger(this.getClass());
	private String stageDirectoryName = null;
	
	
	public LetterStagingManager(Person sender, Date stageDate) {
		super();
		stageDirectoryName = CoreServiceLocator
			.getConfiguration().getEmailStagingDirectory(sender, stageDate);
		FileUtil.createDirectoryIfNotExist(stageDirectoryName);
	}

	public String getStagingDirectoryFullPath() {
		return(this.stageDirectoryName);
	}
	
	public void saveTemplateToStagingDirectory(String templateText) {
		String templateFileName = stageDirectoryName + "/" +
				TEMPLATE_FILE_NAME;
		FileUtil.saveContentToFile(templateFileName, templateText);
	}	

	public void saveSubject(String subject) {
		String subjectFileName = stageDirectoryName + "/" +
				SUBJECT_FILE_NAME;
		FileUtil.saveContentToFile(subjectFileName, subject);
	}
	
	public String getSubject(Person recipient) {
		String subjectFileName = this.getRecipientSubjectFilePath(recipient);
		log.info("Looking for subject specific to recipient in file: " + subjectFileName);
		String subject = null;
		try {
			subject = FileUtil.getFileContents(subjectFileName);
			log.info("Found recipient-specific subject file, subject = " + subject);
		} catch(Exception ex) {
			log.info("Could not find recipient-specific subject, will use default");
		}
		
		if (subject == null)
			subject = this.getDefaultSubject();
		
		return(subject);
	}
	
	public String getDefaultSubject() {
		String subjectFileName = stageDirectoryName + "/" +
		SUBJECT_FILE_NAME;
		return(FileUtil.getFileContents(subjectFileName));
	}

	private String getRecipientLetterFilePath(Person recipient) {
		String outputFileName = this.stageDirectoryName + "/" + "recip_" + recipient.getId();
		return(outputFileName);
	}

	private String getRecipientSubjectFilePath(Person recipient) {
		String outputFileName = this.stageDirectoryName + "/" + "subject_" + recipient.getId();
		return(outputFileName);
	}
	
	/*
	 * 
	 */
	public void createEmailToPerson(Person recipient, Map<String, Object> commonReportParameterMap) {
		log.info("createEmailToPerson() - person: " + recipient.getLastName());
		log.info("createEmailToPerson() - number of template parameters: " + commonReportParameterMap.size());
		FreeMarkerManager freeMarkerManager = new FreeMarkerManager(this.stageDirectoryName);
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("recipient", recipient);
		parameterMap.putAll(commonReportParameterMap);
		
		String outputFileName = this.getRecipientLetterFilePath(recipient);
		try {
			FileWriter writer = new FileWriter(outputFileName);
			freeMarkerManager.processTemplate(writer, TEMPLATE_FILE_NAME, parameterMap);
			writer.close();
		} catch (Exception ex) {
			log.error("Exception creating text from template", ex);
		}
	}
	
	public String getLetterContents(Person recipient) {
		String filePath = this.getRecipientLetterFilePath(recipient);
		String letterContents = FileUtil.getFileContents(filePath);
		return(letterContents);
	}
	
	public void sendAll(Person sender) {
		log.info("Sendig email to recipients");
		
		SendRecipientLetterAction action = new SendRecipientLetterAction(this, sender);
		this.doToRecipientLetters(action);
	}
	
	public void doToRecipientLetters(RecipientLetterAction action) {
		File directory = new File(this.getStagingDirectoryFullPath());
		File[] files = directory.listFiles();
		log.info("Performing action on directory files" +
				"\r\n - Directory = " + this.getStagingDirectoryFullPath() + 
				"\r\n - # of file = " + files.length);
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			String fileName = file.getName();
			if (fileName.startsWith("recip_")) {
				String recipientIdStr = fileName.substring("recip_".length());
				Long recipientId = new Long(recipientIdStr);
				Person recipient = CoreServiceLocator.getPersonService().findPersonById(recipientId);
				action.execute(recipient, file);
			}
		}
	}
	
	
	public void  saveSubject(Person recipient, String subject) {
		String outputFileName = this.getRecipientSubjectFilePath(recipient);
		try {
			FileWriter file = new FileWriter(outputFileName);
			file.write(subject);
			file.close();
		} catch (Exception ex) {
			throw new SystemException("Exception saving file: " + outputFileName, ex);
		}
	}
	
	public void saveBody(Person recipient, String body) {
		String outputFileName = this.getRecipientLetterFilePath(recipient);
		try {
			FileWriter file = new FileWriter(outputFileName);
			file.write(body);
			file.close();
		} catch (Exception ex) {
			throw new SystemException("Exception saving file: " + outputFileName, ex);
		}
		
	}
	
}
